package com.myblog.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.myblog.domain.contants.GlobalConstants;
import com.myblog.domain.entity.LoginUser;
import com.myblog.domain.entity.User;
import com.myblog.mapper.MenuMapper;
import com.myblog.mapper.UserMapper;
import com.myblog.services.MenuService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    UserMapper userMapper;

    @Resource
    MenuMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询用户信息
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName,username);
        User user = userMapper.selectOne(queryWrapper);
        if(!Objects.nonNull(user)){
            throw new RuntimeException("用户不存在");
        }
        // TODO:查询权限信息封装
        // TODO:如果是后台用户才需要查询权限封装
        if(user.getType().equals(GlobalConstants.TYPE_ADMIN)){
            List<String> Perms = mapper.selectPermsByUserID(user.getId());
            return new LoginUser(user,Perms);
        }
        return new LoginUser(user,null);
    }


}
